import React, { useMemo, useState, useEffect } from 'react'
import { 
  NavBar,
  List,
  Button,
  SwipeAction,
  Empty,
  Toast
} from 'antd-mobile'

import './index.css'
import { useNavigate } from 'react-router-dom'
import { hasValidToken } from '../../utils/auth'

interface Message {
  id: number
  type: 'system' | 'health' | 'appointment' | 'medicine' | 'doctor'
  title: string
  content: string
  time: string
  unread: boolean
  priority: 'high' | 'medium' | 'low'
  sender?: string
}

/**
 * 消息中心页面组件
 * 用于展示和管理各类消息通知
 */
function Index() {
  const nav = useNavigate()
  const [isAuthenticated, setIsAuthenticated] = useState(false)
  const [isLoading, setIsLoading] = useState(true)

  // 模拟消息数据
  const messages: Message[] = [
    {
      id: 1,
      type: 'system',
      title: '系统通知',
      content: '欢迎使用妙手医生应用，您的账户已成功激活',
      time: '刚刚',
      unread: true,
      priority: 'high',
      sender: '系统管理员'
    },
    {
      id: 2,
      type: 'health',
      title: '健康提醒',
      content: '记得按时服药，保持健康作息，建议每天运动30分钟',
      time: '2小时前',
      unread: true,
      priority: 'medium',
      sender: '健康助手'
    },
    {
      id: 3,
      type: 'appointment',
      title: '预约确认',
      content: '您的预约已确认，请于明天下午2点准时就诊，地点：内科门诊3号诊室',
      time: '1天前',
      unread: false,
      priority: 'high',
      sender: '预约系统'
    },
    {
      id: 4,
      type: 'medicine',
      title: '用药提醒',
      content: '请按时服用降压药，每日两次，饭后服用',
      time: '2天前',
      unread: false,
      priority: 'medium',
      sender: '用药助手'
    },
    {
      id: 5,
      type: 'doctor',
      title: '医生回复',
      content: '您的检查报告已出，各项指标正常，请继续保持良好的生活习惯',
      time: '3天前',
      unread: false,
      priority: 'low',
      sender: '张医生'
    },
  ]

  // 过滤消息
  const filteredMessages = useMemo(() => {
    return messages
  }, [messages])

  // 检查token状态
  useEffect(() => {
    const checkAuth = () => {
      const hasToken = hasValidToken()
      setIsAuthenticated(hasToken)
      setIsLoading(false)
    }
    checkAuth()
  }, [])

  // 处理登录跳转
  const handleLogin = () => {
    nav('/login')
  }

  // 如果正在加载，显示加载状态
  if (isLoading) {
    return (
      <div className="index-container">
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '100vh',
          fontSize: '16px',
          color: '#666'
        }}>
          加载中...
        </div>
      </div>
    )
  }

  // 如果没有token，显示登录提示页面
  if (!isAuthenticated) {
    return (
      <div className="index-container">
        <NavBar 
          className="page-header"
          backArrow={false}
          style={{
            '--height': '44px',
            '--border-bottom': '1px solid #f0f0f0'
          }}
        >
          <div className="header-content">
            <div className="header-title">
              <h2>医生消息</h2>
            </div>
            {/* <div className="header-actions">
              <div style={{
                display: 'flex',
                gap: '8px',
                padding: '4px 8px',
                backgroundColor: '#f5f5f5',
                borderRadius: '16px'
              }}>
                <span style={{ fontSize: '12px', color: '#666' }}>⋮</span>
                <span style={{ fontSize: '12px', color: '#666' }}>−</span>
                <span style={{ fontSize: '12px', color: '#666' }}>⊙</span>
              </div>
            </div> */}
          </div>
        </NavBar>

        <div style={{ 
          display: 'flex', 
          flexDirection: 'column',
          justifyContent: 'center', 
          alignItems: 'center', 
          height: 'calc(100vh - 44px)',
          padding: '20px',
          textAlign: 'center'
        }}>
          {/* 空状态插图 */}
          <div style={{
            position: 'relative',
            marginBottom: '40px'
          }}>
            {/* 主容器 */}
            <div style={{
              width: '120px',
              height: '80px',
              backgroundColor: '#f0f0f0',
              borderRadius: '8px',
              border: '2px solid #e0e0e0',
              position: 'relative',
              marginBottom: '20px'
            }}>
              {/* 容器内部装饰 */}
              <div style={{
                position: 'absolute',
                top: '10px',
                left: '10px',
                right: '10px',
                height: '4px',
                backgroundColor: '#e0e0e0',
                borderRadius: '2px'
              }} />
              <div style={{
                position: 'absolute',
                top: '20px',
                left: '10px',
                right: '10px',
                height: '4px',
                backgroundColor: '#e0e0e0',
                borderRadius: '2px'
              }} />
            </div>
            
            {/* 对话气泡 */}
            <div style={{
              position: 'absolute',
              top: '-30px',
              right: '-20px',
              width: '60px',
              height: '40px',
              backgroundColor: '#f0f0f0',
              borderRadius: '20px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              border: '2px solid #e0e0e0'
            }}>
              <div style={{
                display: 'flex',
                gap: '2px'
              }}>
                <div style={{
                  width: '4px',
                  height: '4px',
                  backgroundColor: '#999',
                  borderRadius: '50%'
                }} />
                <div style={{
                  width: '4px',
                  height: '4px',
                  backgroundColor: '#999',
                  borderRadius: '50%'
                }} />
                <div style={{
                  width: '4px',
                  height: '4px',
                  backgroundColor: '#999',
                  borderRadius: '50%'
                }} />
              </div>
            </div>
            
            {/* 装饰性云朵 */}
            <div style={{
              position: 'absolute',
              top: '-10px',
              left: '-15px',
              width: '30px',
              height: '20px',
              backgroundColor: '#f0f0f0',
              borderRadius: '15px',
              opacity: 0.6
            }} />
            <div style={{
              position: 'absolute',
              bottom: '10px',
              right: '-10px',
              width: '25px',
              height: '15px',
              backgroundColor: '#f0f0f0',
              borderRadius: '12px',
              opacity: 0.4
            }} />
          </div>
          
          <Button
            block
            color="primary"
            size="large"
            onClick={handleLogin}
            style={{
              '--border-radius': '24px',
              maxWidth: '200px',
              backgroundColor: '#1890ff',
              color: 'white'
            }}
          >
            登录后查看
          </Button>
        </div>
      </div>
    )
  }



  // 获取优先级颜色
  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return '#ff4d4f'
      case 'medium': return '#fa8c16'
      case 'low': return '#52c41a'
      default: return '#666'
    }
  }

  // 标记消息为已读
  const markAsRead = (messageId: number) => {
    const message = messages.find(msg => msg.id === messageId)
    if (message) {
      message.unread = false
      Toast.show('已标记为已读')
      // 这里可以调用API更新消息状态
    }
  }

  // 删除消息
  const deleteMessage = (messageId: number) => {
    const index = messages.findIndex(msg => msg.id === messageId)
    if (index > -1) {
      messages.splice(index, 1)
      Toast.show('消息已删除')
      // 这里可以调用API删除消息
    }
  }

  // 标记所有消息为已读
  const markAllAsRead = () => {
    messages.forEach(msg => msg.unread = false)
    Toast.show('已全部标记为已读')
  }

  // 清空所有消息
  const clearAllMessages = () => {
    if (confirm('确定要清空所有消息吗？此操作不可恢复。')) {
      messages.length = 0
      Toast.show('已清空所有消息')
    }
  }

// 处理消息点击，临时绕过 Toast 直接跳转到 /message 页面
const handleMessageClick = (message: Message) => {
  console.log('点击消息:', message.title)
  // 存储选中的消息，供聊天页读取
  localStorage.setItem('selectedMessage', JSON.stringify(message))
  // 临时直接跳转，避免 antd-mobile Toast 在 React 19 下报错
  nav('/message')
}

  return (
    <div className="index-container">
      {/* 顶部导航栏 */}
      <NavBar 
        className="page-header"
        backArrow={false}
        style={{
          '--height': '44px',
          '--border-bottom': '1px solid #f0f0f0'
        }}
      >
        <div className="header-content">
          <div className="header-title">
            <h2>消息中心</h2>
          </div>
        </div>
      </NavBar>





      {/* 消息列表 */}
      <div className="messages-section">
        {filteredMessages.length > 0 ? (
          <List>
            {filteredMessages.map((message) => (
              <SwipeAction
                key={message.id}
                rightActions={[
                  {
                    key: 'read',
                    text: message.unread ? '已读' : '已读',
                    color: message.unread ? '#1890ff' : '#52c41a',
                    onClick: () => markAsRead(message.id)
                  },
                  {
                    key: 'delete',
                    text: '删除',
                    color: '#ff4d4f',
                    onClick: () => deleteMessage(message.id)
                  }
                ]}
              >
                <List.Item
                  onClick={() => handleMessageClick(message)}
                  className={`message-item ${message.unread ? 'unread' : ''}`}
                  prefix={
                    <div className="message-avatar">
                      <div className="avatar-icon">
                        📧
                      </div>
                      {message.unread && <div className="unread-dot"></div>}
                    </div>
                  }
                  title={
                    <div className="message-header">
                      <span className="message-title">{message.title}</span>
                      <span 
                        className="priority-badge"
                        style={{ backgroundColor: getPriorityColor(message.priority) }}
                      >
                        {message.priority === 'high' ? '高' : message.priority === 'medium' ? '中' : '低'}
                      </span>
                    </div>
                  }
                  description={
                    <div className="message-content">
                      <p className="message-text">{message.content}</p>
                      <div className="message-meta">
                        <span className="message-sender">{message.sender}</span>
                        <span className="message-time">{message.time}</span>
                      </div>
                    </div>
                  }
                  arrow={true}
                />
              </SwipeAction>
            ))}
          </List>
        ) : (
          <Empty
            description="暂无消息"
            image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
          />
        )}
      </div>

      {/* 快捷操作 */}
      <div className="quick-actions">
        <Button
          block
          fill="outline"
          onClick={markAllAsRead}
          style={{
            '--border-radius': '24px',
            '--border-color': '#1890ff',
            '--text-color': '#1890ff'
          }}
        >
          全部已读
        </Button>
        <Button
          block
          fill="outline"
          onClick={clearAllMessages}
          style={{
            '--border-radius': '24px',
            '--border-color': '#ff4d4f',
            '--text-color': '#ff4d4f'
          }}
        >
          清空消息
        </Button>
      </div>
    </div>
  )
}

export default Index
